#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
API接口测试脚本
用于测试后端各个接口是否正常工作
"""

import requests
import json
from datetime import datetime

# 配置
BASE_URL = 'http://127.0.0.1:8080'
HEADERS = {'Content-Type': 'application/json'}


def print_section(title):
    """打印区块标题"""
    print("\n" + "=" * 60)
    print(f" {title} ".center(60, "="))
    print("=" * 60)


def print_test(test_name):
    """打印测试名称"""
    print(f"\n【测试】{test_name}")
    print("-" * 60)


def print_result(success, message):
    """打印测试结果"""
    status = "✓ 成功" if success else "✗ 失败"
    print(f"{status}: {message}")


def test_request(method, url, data=None, params=None):
    """
    发送HTTP请求并返回结果
    """
    try:
        if method == 'GET':
            response = requests.get(url, params=params, headers=HEADERS, timeout=5)
        elif method == 'POST':
            response = requests.post(url, json=data, headers=HEADERS, timeout=5)
        elif method == 'PUT':
            response = requests.put(url, json=data, headers=HEADERS, timeout=5)
        elif method == 'DELETE':
            response = requests.delete(url, json=data, headers=HEADERS, timeout=5)
        else:
            return None, "不支持的HTTP方法"
        
        return response.json(), None
    except requests.exceptions.ConnectionError:
        return None, "连接失败：请确保服务器已启动"
    except requests.exceptions.Timeout:
        return None, "请求超时"
    except json.JSONDecodeError:
        return None, "响应不是有效的JSON格式"
    except Exception as e:
        return None, f"请求失败: {str(e)}"


def check_server():
    """检查服务器是否运行"""
    print_test("检查服务器状态")
    try:
        response = requests.get(BASE_URL, timeout=2)
        print_result(True, "服务器正在运行")
        return True
    except:
        print_result(False, f"无法连接到服务器 {BASE_URL}")
        print("请确保服务器已启动：python manage.py runserver 0.0.0.0:8080")
        return False


def test_user_check():
    """测试检查用户是否存在"""
    print_test("检查用户是否存在")
    
    # 测试存在的用户
    url = f'{BASE_URL}/user/check'
    params = {'phone': '13800138000'}
    result, error = test_request('GET', url, params=params)
    
    if error:
        print_result(False, error)
        return False
    
    if result.get('code') == 200:
        print_result(True, "成功查询到用户")
        return True
    else:
        print_result(False, f"查询失败: {result}")
        return False


def test_login():
    """测试用户登录"""
    print_test("用户登录")
    
    url = f'{BASE_URL}/auth/login'
    data = {
        'phone': '13800138000',
        'password': 'admin123'
    }
    
    result, error = test_request('POST', url, data=data)
    
    if error:
        print_result(False, error)
        return None
    
    if result.get('code') == 200:
        user_data = result.get('data', {})
        print_result(True, f"登录成功: 用户 {user_data.get('username')}")
        print(f"  用户ID: {user_data.get('id')}")
        print(f"  手机号: {user_data.get('phone')}")
        print(f"  余额: {user_data.get('money')}")
        print(f"  管理员: {user_data.get('is_admin')}")
        return user_data
    else:
        print_result(False, f"登录失败: {result.get('error', '未知错误')}")
        return None


def test_register():
    """测试用户注册"""
    print_test("用户注册")
    
    url = f'{BASE_URL}/user/user'
    # 生成随机用户ID和手机号（基于时间戳）
    timestamp = datetime.now().strftime("%H%M%S")
    data = {
        'id': f'test{timestamp}',
        'username': f'测试用户{timestamp}',
        'phone': f'139{timestamp}0001',
        'password': '12345678'
    }
    
    result, error = test_request('POST', url, data=data)
    
    if error:
        print_result(False, error)
        return None
    
    if result.get('code') == 200:
        user_data = result.get('data', {})
        print_result(True, f"注册成功: {user_data.get('username')}")
        print(f"  用户ID: {user_data.get('id')}")
        print(f"  手机号: {user_data.get('phone')}")
        return user_data
    else:
        error_msg = result.get('error', '未知错误')
        # 如果是已注册，不算失败
        if '已注册' in error_msg or '已被注册' in error_msg:
            print_result(True, f"用户已存在（正常）: {error_msg}")
            return {'id': data['id'], 'phone': data['phone']}
        else:
            print_result(False, f"注册失败: {error_msg}")
            return None


def test_get_user():
    """测试获取用户信息"""
    print_test("获取用户信息")
    
    url = f'{BASE_URL}/user/user'
    params = {'id': 'admin001'}
    
    result, error = test_request('GET', url, params=params)
    
    if error:
        print_result(False, error)
        return False
    
    if result.get('code') == 200:
        user_data = result.get('data', {})
        print_result(True, f"获取成功: {user_data.get('username')}")
        print(f"  用户ID: {user_data.get('id')}")
        print(f"  手机号: {user_data.get('phone')}")
        print(f"  余额: {user_data.get('money')}")
        return True
    else:
        print_result(False, f"获取失败: {result.get('error', '未知错误')}")
        return False


def test_get_kinds():
    """测试获取外卖分类"""
    print_test("获取外卖分类")
    
    url = f'{BASE_URL}/kind/kind'
    
    result, error = test_request('GET', url)
    
    if error:
        print_result(False, error)
        return False
    
    if result.get('code') == 200:
        kinds = result.get('data', [])
        print_result(True, f"获取成功: 共 {len(kinds)} 个分类")
        for kind in kinds[:5]:  # 只显示前5个
            print(f"  - {kind.get('type')}: {kind.get('content')}")
        if len(kinds) > 5:
            print(f"  ... 还有 {len(kinds) - 5} 个分类")
        return True
    else:
        print_result(False, f"获取失败: {result.get('error', '未知错误')}")
        return False


def test_get_takeouts():
    """测试获取外卖列表"""
    print_test("获取外卖列表")
    
    url = f'{BASE_URL}/takeout/takeout-all'
    
    result, error = test_request('GET', url)
    
    if error:
        print_result(False, error)
        return False
    
    code = result.get('code')
    if code == 200:
        takeouts = result.get('data', [])
        print_result(True, f"获取成功: 共 {len(takeouts)} 个外卖")
        for takeout in takeouts[:3]:  # 只显示前3个
            print(f"  - {takeout.get('takeout_name')}: ¥{takeout.get('price')}")
        if len(takeouts) > 3:
            print(f"  ... 还有 {len(takeouts) - 3} 个外卖")
        return True
    elif code == 102001:  # 外卖列表为空
        print_result(True, "外卖列表为空（数据库中暂无外卖数据）")
        return True
    else:
        print_result(False, f"获取失败: {result.get('error', '未知错误')}")
        return False


def run_all_tests():
    """运行所有测试"""
    print_section("交易平台API测试")
    
    print(f"测试时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"服务器地址: {BASE_URL}")
    
    # 检查服务器
    if not check_server():
        return
    
    # 统计结果
    results = []
    
    # 用户相关测试
    print_section("用户功能测试")
    results.append(("检查用户", test_user_check()))
    results.append(("用户登录", test_login() is not None))
    results.append(("用户注册", test_register() is not None))
    results.append(("获取用户信息", test_get_user()))
    
    # 外卖相关测试
    print_section("外卖功能测试")
    results.append(("获取分类", test_get_kinds()))
    results.append(("获取外卖列表", test_get_takeouts()))
    
    # 显示测试结果统计
    print_section("测试结果统计")
    
    success_count = sum(1 for _, result in results if result)
    total_count = len(results)
    success_rate = (success_count / total_count * 100) if total_count > 0 else 0
    
    print(f"\n总测试数: {total_count}")
    print(f"成功: {success_count}")
    print(f"失败: {total_count - success_count}")
    print(f"成功率: {success_rate:.1f}%")
    
    print("\n详细结果:")
    for test_name, result in results:
        status = "✓" if result else "✗"
        print(f"  {status} {test_name}")
    
    print("\n" + "=" * 60)
    
    if success_count == total_count:
        print("🎉 所有测试通过！系统运行正常。")
    else:
        print("⚠️  部分测试失败，请检查错误信息。")
    
    print("=" * 60)


if __name__ == '__main__':
    try:
        run_all_tests()
    except KeyboardInterrupt:
        print("\n\n测试被用户中断")
    except Exception as e:
        print(f"\n\n测试过程中发生错误: {e}")
        import traceback
        traceback.print_exc()

